<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* 
*/
class AdminUser extends MY_Controller
{

	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('User/AdminUserModel','admin');
	}

	public function index()
	{
		$this->load->view('admin_user');
	}


	//数据列表
	public function get_list()
	{
		$keyword = $this->uri->segment(3);

		$res = $this->admin->get_admin_data($keyword);
		if ($res) 
		{
			$data['list'] = $res;
			$data['status'] = 200;
			$data['message'] = '获取成功！';
		}
		else
		{
			$data['status'] = 400;
			$data['message'] = '数据获取失败！';
		}

		echo json_encode($data);exit();

	}


	//添加、编辑页
	public function add_edit_admin()
	{
		$data['admin_id'] = intval($this->uri->segment(3));
		
		//编辑
		if ($data['admin_id'] > 0) 
		{
			$res = $this->admin->admin_data_row($data['admin_id']);
		}

		$data['name'] = isset($res['name']) ? $res['name'] : '';
		$data['remarks'] = isset($res['remarks']) ? $res['remarks'] : '';
		$data['headimg'] = isset($res['headimg']) ? $res['headimg'] : '';
		//图片上传地址
		$data['image_upload_url'] = $this->image_load_url;

		$this->load->view('add_edit_admin',$data);
	}


	//处理添加
	public function insert_admin_user()
	{
		$field = array('name','password','remarks', 'headimg');

		$arr = $this->input->post($field, TRUE);

		$admin_id = $this->input->post('admin_id');

		//添加
		if (empty($admin_id)) 
		{
			$res = $this->admin->insert_data($arr);

			if ($res) 
			{
				if (!empty($res['name'])) 
				{
					$data['status'] = 400;
					$data['message'] = '填写的用户名已存在！';
					echo json_encode($data);exit();
				}

				if ($res['admin_id'] > 0) 
				{
					$data['status'] = 200;
					$data['message'] = '添加成功！';
				}

			}
			else
			{
				$data['status'] = 400;
				$data['message'] = '添加失败！';
			}
		}

		//更新
		else
		{
			$res = $this->admin->update_user_data($arr, $admin_id);

			if ($res) 
			{
				if (isset($res['name'])) {
					$data['status'] = 400;
					$data['message'] = '填写的用户名已存在！';
					echo json_encode($data);exit();
				}

				$data['status'] = 200;
				$data['message'] = '更新成功！';
			}
			else
			{
				$data['status'] = 400;
				$data['message'] = '更新失败！';
			}
		}

		echo json_encode($data);exit();

	}



	//删除管理员
	public function delete_user()
	{
		$admin_id = $this->input->get('id', true);

		if ($admin_id == 1) {
			$data['status'] = 400;
			$data['message'] = '不可删除超级管理员！';
			echo json_encode($data);exit();
		}


		$res = $this->admin->delete_admin_user($admin_id);

		if ($res){
			$data['status'] = 200;
			$data['message'] = '删除成功！';
		}
		else{
			$data['status'] = 400;
			$data['message'] = '删除失败！';
		}

		echo json_encode($data);exit();

	}
	
	
}


?>